package middleware

import (
	"autoclave/global"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"net/http"
	"strings"
	"time"
)

func Cors() gin.HandlerFunc {

	return func(context *gin.Context) {
		method := context.Request.Method

		context.Header("Access-Control-Allow-Origin", "*")
		context.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token, x-token")
		context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PATCH, PUT")
		context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		context.Header("Access-Control-Allow-Credentials", "true")

		if method == "OPTIONS" {
			//context.AbortWithStatus(http.StatusNoContent)
			context.AbortWithStatus(http.StatusOK)
		}
	}

}

func LoggerToFile() gin.HandlerFunc {

	return func(c *gin.Context) {
		// 开始时间
		startTime := time.Now()
		// 处理请求
		c.Next()
		// 结束时间
		// 执行时间
		latencyTime := time.Since(startTime).String()
		// 请求方式
		reqMethod := c.Request.Method
		// 请求路由
		reqUri := c.Request.RequestURI
		// 状态码
		statusCode := c.Writer.Status()
		// 请求IP
		clientIP := c.ClientIP()
		// 日志格式
		global.JLogger.WithFields(logrus.Fields{
			"status_code":  statusCode,
			"latency_time": latencyTime,
			"client_ip":    clientIP,
			"req_method":   reqMethod,
			"req_uri":      reqUri,
		}).Info()
	}
}

func CustomRecovery() gin.HandlerFunc {
	return gin.CustomRecovery(func(ctx *gin.Context, any interface{}) {
		defer func() {
			if err := recover(); err != nil {
				fmt.Println("log failed: ", err)
			}
		}()
		global.JLogger.WithFields(logrus.Fields{
			"status_code": 500,
			"panic_info":  fmt.Sprintf("%s", any),
			"req_uri":     ctx.Request.RequestURI,
		}).Error()
		ctx.String(500, "%s %v", ctx.Request.RequestURI, any)
	})
}

func getCmd(path string) string {
	pathArr := strings.Split(path, "/")
	if len(pathArr) == 4 {
		return pathArr[2] + "/" + pathArr[3]
	} else if len(pathArr) == 3 {
		return pathArr[2]
	} else {
		return ""
	}
}

func CheckLogin(ctx *gin.Context) {
	//pathInfo := strings.Split(ctx.Request.URL.String(), "?")
	//path := pathInfo[0]
	//
	//controller := getCmd(path)
	//allowList := make(map[string]int)
	//allowList["test"] = 1
	//allowList["captcha"] = 1
}
